package com.zsl.swing.redis.desktop.utils;

import com.zsl.swing.redis.desktop.window.list.oftenusekey.OftenUseKeyPatternListNode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class OffUseKeyFileUtils {


    private static final String BASE_DIR = ConfigUtils.getRealBasePath("often-use-keys");

    private static final String FILE_NAME_F = "%s_%s_often_use_key.txt";

    private static final String DELIMITER = "!!!&&&!!!";


    private OffUseKeyFileUtils(){}

    static {
        File file = new File(BASE_DIR);
        if(!file.exists()){
            file.mkdirs();
        }
    }

    public static List<OftenUseKeyPatternListNode>  readListFromFile(String uniqueId, int dbIndex){
        List<String> lineList = TextFileReadUtils.readLineList(buildFileName(uniqueId, dbIndex));

        List<OftenUseKeyPatternListNode> targetList = new ArrayList<>(lineList.size());

        for (String line : lineList) {
            if(!StringUtils.isEmpty(line)){

                OftenUseKeyPatternListNode node = new OftenUseKeyPatternListNode();
                node.setUniqueId(uniqueId);
                node.setDbIndex(dbIndex);

                String[] split = line.split(DELIMITER);
                node.setOftenUseKeyPattern(split[0]);
                node.setUpdateMils(Long.parseLong(split[1]));

                targetList.add(node);

            }
        }

        return targetList;


    }


    public static void writeListToFile(String uniqueId, int dbIndex, List<OftenUseKeyPatternListNode> dataList){
        List<String> lineList = new ArrayList<>();

        for (OftenUseKeyPatternListNode node : dataList) {
            String line = new StringBuilder(node.getOftenUseKeyPattern()).append(DELIMITER).append(node.getUpdateMils()).toString();
            lineList.add(line);
        }


        try {
            TextFileWriter.generateTxtFile(buildFileName(uniqueId, dbIndex), lineList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private static String buildFileName(String uniqueId, int dbIndex){
        return BASE_DIR + String.format(FILE_NAME_F, uniqueId, dbIndex);
    }
}
